package com.itcast.tcp.server.decoder_tcp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-23 09:59
 **/
public class MyDecoder extends ReplayingDecoder<Void> {
    private Queue<Integer> values = new LinkedList<>();
    
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext,
                          ByteBuf byteBuf, List<Object> list) throws Exception {
        // Revert the state of the variable that might have been changed
// since the last partial decode
        values.clear();
        
        //message CONTAINS 2 integers
        values.offer(byteBuf.readInt());
        values.offer(byteBuf.readInt());
        
        //同⼀个线程也可能多次调⽤decode()⽅法。在decode中修
        // 改ReplayingDecoder的类变量时必须⼩⼼谨慎。
        assert values.size() == 2;
        list.add(values.poll() + values.poll());
    }
}
